import cutils from '../../js/common/core-utils.js';
import '../../js/common/table-col-utils.js';

$(function() {
	//初始化datagrid
	initTable();

	//按回车事件查询
	$(document).keydown(function() {
		if (event.keyCode == 13) {
			doSearch();
		}
	});

	//权限处理，对带有hi-auth-sign样式的按钮继续权限检查，对应用户没有权限的按钮继续隐藏
	cutils.doAuthSign();
});

self.initTable = function() {
	$('#data-table').datagrid({
		url: "/" + cutils.webApp + "/user/list?_time=" + cutils.now(),
		method: 'get',
		idField: "userId",
		animate: true,
		fit: true,
		fitColumns: false,
		pagination: true,
		pageSize: 50,
		pageList: [20, 50, 100, 200, 500],
		rownumbers: false,
		loadMsg: false,
		resizeHandle: 'both',
		singleSelect: false,
		checkOnSelect: false,
		selectOnCheck: false,
		emptyMsg: '无数据',
		onBeforeLoad: function(param) {
			param["pageNo"] = param.page;
			param["pageSize"] = param.rows;
			param["sortType"] = param.order;
			param["sortField"] = param.sort;
		},
		onLoadSuccess: function(data) {
			layui.form.render();
			$('#data-table').treegrid('unselectAll');
			$('#data-table').treegrid('uncheckAll');
			cutils.doAuthSign();
		},
		onLoadError: function() {
			$(".datagrid-body").html("<div style='width: 100%; height: 50px; line-height: 50px; text-align: center;font-size: 14px;'>数据加载出错</div>");
		},
		loadFilter: function(data, parentId) {
			return {
				total: data.data.count,
				rows: data.data.dataList
			};
		},
		columns: [[{
			field: 'username',
			title: '登录账号',
			width: 100,
			sortable: true
		}, {
			field: 'fullname',
			title: '姓名',
			width: 80,
			sortable: true
		}, {
			field: 'orgnames',
			title: '部门',
			width: 190,
			formatter: function(value, row, index) {
				return "<span title='" + value + "'>" + value + "</span>";
			}
		}, {
			field: 'rolenames',
			title: '角色',
			width: 190,
			formatter: function(value, row, index) {
				return "<span title='" + value + "'>" + value + "</span>";
			}
		}, {
			field: 'mobilenumber',
			title: '手机号码',
			width: 120
		}, {
			field: 'officephone',
			title: '办公电话',
			hidden: true,
			width: 120
		}, {
			field: 'email',
			title: '电子邮箱',
			width: 160
		}, {
			field: 'desc',
			title: '备注信息',
			width: 200,
			hidden: true
		}, {
			field: 'updatetime',
			title: '更新时间',
			width: 150,
			align: 'center',
			sortable: true,
			hidden: true,
			formatter: function(value, row, index) {
				return value.length > 16 ? value.substring(0, 16) : value;
			}
		}, {
			field: 'status',
			title: '是否禁用',
			align: 'center',
			width: 80,
			formatter: function(value, row, index) {
				return '<span class="layui-form" id="user-status-span-' + index + '" ><input tipId="#user-status-span-' + index + '" type="checkbox" name="user-status" userId="' + row.userId + '" title="禁用" lay-filter="user-status" ' + (row.status == 1 ? 'checked' : '') + '></span>';
			}
		}, {
			field: 'opts',
			title: '操作',
			width: 180,
			align: 'center',
			formatter: function(value, row, index) {
				let html = '<div title="编辑用户" data-authcode="uums.user.edit" class="hi-small-btn hi-small-normal-btn hi-transition hi-auth-sign" onclick="doEditUser(' + row.userId + ');">';
				html += '<i class="fa fa-pencil-square-o" aria-hidden="true"></i>';
				html += '</div>';

				html += '<div title="删除用户" data-authcode="uums.user.del" class="hi-small-btn hi-small-txt-red-btn hi-transition hi-auth-sign" onclick="doDelUser(' + row.userId + ');">';
				html += '<i class="fa fa-trash-o" aria-hidden="true"></i>';
				html += '</div>';

				html += '<div data-authcode="uums.user.reset.password" class="hi-small-btn hi-small-normal-btn hi-transition hi-auth-sign" onclick="doResetPassword(' + row.userId + ');" id="hi-more-btn-' + row.userId + '">';
				html += '<i class="fa fa-lock" aria-hidden="true"></i>';
				html += '<span>重置密码</span>';
				html += '</div>';
				return html;
			}
		}]]
	});

	layui.form.on('checkbox(user-status)', function(obj) {
		if (cutils.hasNotAuthCode("uums.user.edit")) {
			$(obj.elem).prop("checked", !obj.elem.checked);
			layui.form.render();
			layer.tips('没有操作权限', $(obj.elem).attr("tipId"), {
				tips: 1,
				time: 1000
			});
			return false;
		}
		doEidtUserStatus(obj);
	});
}

self.doSearch = function() {
	var unlock = $("#q-status-unlock").is(":checked");
	var lock = $("#q-status-lock").is(":checked");

	var queryParams = {};
	queryParams["username"] = $("#q-username").val();
	queryParams["fullname"] = $("#q-fullname").val();
	queryParams["orgId"] = $("#q-org-id").val();
	queryParams["status"] = unlock && lock ? "" : !unlock && !lock ? "" : unlock ? 0 : 1;
	$('#data-table').datagrid('load', queryParams);
}

self.doEidtUserStatus = function(obj) {
	var params = {
		"userId": $(obj.elem).attr("userId"),
		"status": obj.elem.checked ? 1 : 0,
	};

	$.ajax({
		type: "put",
		url: "/" + cutils.webApp + "/user/status?_time=" + cutils.now(),
		data: params,
		dataType: 'json',
		success: function(result) {
			if (cutils.equals(result.status, 200)) {
				layer.msg(result.message, { icon: 1, time: 1000 });
				return;
			}

			$(obj.elem).prop("checked", !obj.elem.checked);
			layui.form.render();
			layer.msg(result.message, { icon: 7 });
		},
		nerror: function(e) {
			$(obj.elem).prop("checked", !obj.elem.checked);
			layui.form.render();
		}
	});
}

self.doDelUser = function(userId) {
	layer.confirm('确定删除吗?',
		{
			icon: 3,
			title: '温馨提示',
			btn: ['<i class="fa fa-check" style="color: inherit;"></i>确定', '<i class="fa fa-remove" style="color: inherit;"></i>取消'],
			yes: function(index) {
				layer.close(index);
				$.ajax({
					type: "delete",
					url: "/" + cutils.webApp + "/user/" + userId + "?_time=" + cutils.now(),
					dataType: 'json',
					success: function(result) {
						if (cutils.notEquals(result.status, 200)) {
							layer.msg(result.message, { icon: 7 });
							return;
						}
						layer.msg(result.message, { icon: 1, time: 1000 });
						doSearch();
					}
				});
			},
			cancel: function(index) {
				layer.close(index);
			}
		});
}

//新增用户界面
self.doAddUser = function() {
	top.layer.open({
		type: 2,
		title: '新增用户',
		area: ['600px', ($(top.document.body).height() - 50) + 'px'],
		shade: 0.3,
		maxmin: true,
		content: "/" + cutils.webApp + "/views/user/add.html?_time=" + cutils.now(),
		btn: ['<i class="fa fa-check" style="color: inherit;"></i>保存', '<i class="fa fa-remove" style="color: inherit;"></i>取消'],
		yes: function(index, layero) {
			var iframeWin = layero.find('iframe')[0];
			iframeWin.contentWindow.doSubmitHandler(top, self);
		},
		cancel: function(index) {
			top.layer.close(index);
		}
	});
}

//编辑用户界面
self.doEditUser = function(userId) {
	top.layer.open({
		type: 2,
		title: '编辑用户',
		area: ['600px', ($(top.document.body).height() - 50) + 'px'],
		shade: 0.3,
		maxmin: true,
		content: "/" + cutils.webApp + "/views/user/edit.html?userId=" + userId + "&_time=" + cutils.now(),
		btn: ['<i class="fa fa-check" style="color: inherit;"></i>保存', '<i class="fa fa-remove" style="color: inherit;"></i>取消'],
		yes: function(index, layero) {
			var iframeWin = layero.find('iframe')[0];
			iframeWin.contentWindow.doSubmitHandler(top, self);
		},
		cancel: function(index) {
			top.layer.close(index);
		}
	});
}

//重置密码
self.doResetPassword = function(userId) {
	layer.confirm('确定重置密码吗?',
		{
			icon: 3,
			title: '温馨提示',
			btn: ['<i class="fa fa-check" style="color: inherit;"></i>确定', '<i class="fa fa-remove" style="color: inherit;"></i>取消'],
			yes: function(index) {
				layer.close(index);
				var layerLoadIndex = layer.load(1, { shade: 0.3 });
				$.ajax({
					type: "put",
					url: "/" + cutils.webApp + "/user/reset/password?_time=" + cutils.now(),
					data: {
						userId: userId,
					},
					dataType: 'json',
					success: function(result) {
						layer.close(layerLoadIndex);
						if (cutils.notEquals(result.status, 200)) {
							layer.msg(result.message, { icon: 7 });
							return;
						}
						layer.msg(result.message, { icon: 1, time: 1000 });
					}
				});
			},
			cancel: function(index) {
				layer.close(index);
			}
		});
}

//选择部门
self.doSelectOrg = function() {
	top.layer.open({
		type: 2,
		title: '选择部门',
		area: ['320px', '450px'],
		shade: 0.01,
		maxmin: true,
		shadeClose: true,
		content: "/" + cutils.webApp + "/views/org/select.html?singleSelect=true&orgId=" + $("#q-org-id").val() + "&_time=" + cutils.now(),
		btn: ['<i class="fa fa-check" style="color: inherit;"></i>确定', '<i class="fa fa-eraser" style="color: inherit;"></i>清除', '<i class="fa fa-remove" style="color: inherit;"></i>取消'],
		yes: function(index, layero) {
			top.layer.close(index);

			var iframeWin = layero.find('iframe')[0];
			var data = iframeWin.contentWindow.getChecked();
			$("#q-org-id").val(data.orgId);
			$("#q-org-name").val(data.name);

			doSearch();
		},
		btn2: function(index, layero) {
			top.layer.close(index);

			$("#q-org-id").val("");
			$("#q-org-name").val("");

			doSearch();
		}, btn3: function(index, layero) {
			top.layer.close(index);
		},
		cancel: function(index) {
			top.layer.close(index);
		}
	});
}